package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.user.dto.TestUserDTO;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: atguigu
 * @create: 2023-06-20 10:39
 */
@RestController
@RequestMapping("/api/user")
public class PassPortController {

    @Autowired
    private UserInfoService userInfoService;


    /**
     * 用户登录
     *
     * @param userInfo 认证信息: loginName|email|tel 跟 passwd
     * @return
     */
    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        Map<String, Object> loginResult = userInfoService.login(userInfo, request);
        return Result.ok(loginResult);
    }

    /**
     * 退出系统 拿到客户端提交Token,请求头携带Cookie
     *
     * @return
     */
    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader("token") String token) {
        userInfoService.logout(token);
        return Result.ok();
    }


    /**
     * 保存用户信息
     * 如果校验参数失败,将错误信息封装到对象
     *
     * @param bindingResult 必须放在校验对象后面;只有校验参数失败 才有值
     * @param user
     * @return
     */
    @PostMapping("/saveUser")
    public Result saveUser(@Valid @RequestBody TestUserDTO user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //参数验证失败
            String errorMsg = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            return Result.fail().message(errorMsg);

        }
        System.out.println("保存用户成功");
        return Result.ok();
    }
}
